package com.hll.api.filter;

import com.hll.api.util.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author 何龙
 */
@Slf4j
@WebFilter(filterName = "myFilter", urlPatterns = "/*")
public class CrossDomainFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) {
    }

    // 跨域域名设置
    public static final String[] ALLOW_DOMAIN = {
            "http://localhost:8080",
            "http://xhsd.hll666.xyz",
            "http://127.0.0.1:8080",
            "http://39.107.253.13:7777",
            "http://localhost:8081",
            "http://127.0.0.1:8081",
            "http://localhost:8082",
            "http://127.0.0.1:8082",
            "http://localhost:8083",
            "http://127.0.0.1:8083",
    };
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        log.debug( "【{}】请求地址：{}", HttpUtils.getClientIp(request),((HttpServletRequest) req).getRequestURI() );
        // 设置允许多个域名请求
        Set<String> allowOrigins = new HashSet<>(Arrays.asList(ALLOW_DOMAIN));
        String originHeads = request.getHeader("Origin");
        if(allowOrigins.contains(originHeads)) {
            //设置允许跨域的配置
            // 这里填写你允许进行跨域的主机ip（正式上线时可以动态配置具体允许的域名和IP）
            response.setHeader("Access-Control-Allow-Origin", originHeads);
        }else {
            response.setHeader("Access-Control-Allow-Origin", "*");
        }
        response.setHeader( "Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH" );
        response.setHeader( "Access-Control-Max-Age", "3600" );
        response.setHeader( "Access-Control-Allow-Credentials", "true" );
        response.setHeader( "Access-Control-Allow-Headers", "Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization,userToken" );
        if (request.getMethod().equals( HttpMethod.OPTIONS.name() )) {
            response.setStatus( HttpStatus.NO_CONTENT.value() );
        } else {
            chain.doFilter( req, res );
        }
    }

    @Override
    public void destroy() {
    }
}
